package me.xiaoyan.ehr.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.xiaoyan.ehr.dao.VerifyTokenDao;
import me.xiaoyan.ehr.mapper.VerifyTokenMapper;
import me.xiaoyan.ehr.po.EmployeeInfo;
import me.xiaoyan.ehr.po.VerifyToken;
import me.xiaoyan.ehr.service.EmployeeInfoService;
import me.xiaoyan.ehr.service.VerifyTokenService;
import me.xiaoyan.ehr.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;

@Service
public class VerifyTokenServiceImpl extends BaseService<VerifyTokenMapper, VerifyToken>
        implements VerifyTokenService {
    private VerifyTokenDao verifyTokenDao;
    private EmployeeInfoService employeeInfoService;

    @Autowired
    public void setEmployeeInfoService(EmployeeInfoService employeeInfoService) {
        this.employeeInfoService = employeeInfoService;
    }

    @Autowired
    public void setVerifyTokenDao(VerifyTokenDao verifyTokenDao) {
        this.verifyTokenDao = verifyTokenDao;
    }

    private final String CODE_HTML = "$user，你好：<br><br>" +
            "你操作的邮箱验证码为：<span style=\"font-size:20px;color:red\">$code</span>，该验证码$time分钟内有效。<br><br>" +
            "如果该验证码邮件不是由你主动请求发出，请忽略并删除它！";

    @Override
    public void sendCode(String email, int expireTime) {
        try {
            // 验证邮箱是否正确
            EmployeeInfo employeeInfo = employeeInfoService.getByEmail(email);
            if (employeeInfo == null) {
                throw new RuntimeException("邮箱不存在");
            }
            // 生成6位数的随机验证码
            String code = StringUtil.generateCode(6);
            // 保存验证码到数据
            VerifyToken token = new VerifyToken();
            token.setToken(code);
            token.setType("reset_pwd");
            token.setTarget(email);
            Date date = new Date();
            // 设置失效时间
            date.setTime(date.getTime() + expireTime * 1000 * 60);
            token.setExpireTime(date);
            this.save(token);
            // 获取并替换验证码内容
            String html = CODE_HTML.replace("$code", code).replace("$user", email).replace("$time", expireTime + "");
            // 发送邮件
            verifyTokenDao.sendHTML(email, html, "重置密码验证码");
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean validate(String email, String token) {
        QueryWrapper query = new QueryWrapper();
        query.eq("target",email); // 邮箱验证
        query.eq("token",token);
        Date now = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        query.gt("expire_time",dateFormat.format(now));
        int count = count(query);
        return count != 0;
    }

    @Override
    public void deleteAllExpireToken() {
        QueryWrapper query = new QueryWrapper();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
        query.lt("expire_time",dateFormat.format(new Date()));
        remove(query); // 删除所有已经失效的token
    }
}
